package org.framework.lazy.cloud.network.heartbeat.server.netty.advanced;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.*;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.server.AbstractHandleReportClientTransferClientPermeateChannelConnectionSuccessfulTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.springframework.stereotype.Component;

/**
 * 上报 客户端渗透客户端数据传输通道连接成功
 */
@Slf4j
@Component
public class ServerHandleReportClientTransferClientPermeateChannelConnectionSuccessfulTypeAdvanced extends AbstractHandleReportClientTransferClientPermeateChannelConnectionSuccessfulTypeAdvanced<NettyProxyMsg> {
    /**
     * 处理当前数据
     *
     * @param transferChannel       当前通道
     * @param nettyProxyMsg 通道数据
     */
    @Override
    protected void doHandler(Channel transferChannel, NettyProxyMsg nettyProxyMsg) {
        // 创建目标地址连接
        byte[] msgVisitorId = nettyProxyMsg.getVisitorId();
        byte[] msgVisitorPort = nettyProxyMsg.getVisitorPort();
        byte[] msgClientTargetIp = nettyProxyMsg.getClientTargetIp();
        byte[] msgClientTargetPort = nettyProxyMsg.getClientTargetPort();
        byte[] clientId = nettyProxyMsg.getClientId();// 目标客户端ID

        ChannelAttributeKeyUtils.buildClientId(transferChannel, clientId);
        ChannelAttributeKeyUtils.buildVisitorId(transferChannel, msgVisitorId);
        // 绑定访客通道
        NettyTransferChannelContext.pushVisitor(transferChannel,msgVisitorId);
        ChannelContext.ClientChannel clientChannel = ChannelContext.get(clientId);

        NettyProxyMsg clientConnectTagetNettyProxyMsg = new NettyProxyMsg();
        clientConnectTagetNettyProxyMsg.setVisitorId(msgVisitorId);
        clientConnectTagetNettyProxyMsg.setVisitorPort(msgVisitorPort);
        clientConnectTagetNettyProxyMsg.setClientTargetIp(msgClientTargetIp);
        clientConnectTagetNettyProxyMsg.setClientTargetPort(msgClientTargetPort);
        clientConnectTagetNettyProxyMsg.setClientId(clientId);
        clientConnectTagetNettyProxyMsg.setType(MessageType.DISTRIBUTE_CLIENT_TRANSFER_CLIENT_PERMEATE_CHANNEL_CONNECTION_SUCCESSFUL);
        if (clientChannel != null) {
            clientChannel.getChannel().writeAndFlush(clientConnectTagetNettyProxyMsg);
        }else {
            log.error("can not find the client:【】 channel",clientId);
        }



    }
}
